const axios = require('axios')
const pluralize = require('pluralize') // 单词转复数形式
const createNodeHelpers = require('gatsby-node-helpers').default

async function sourceNodes ({actions}, configOptions) {
  const {createNode} = actions
  const { apiURL, contentTypes } = configOptions
  // Post -> posts  Product -> products
  const types = contentTypes.map(type => pluralize(type.toLowerCase()))
  // console.log(types) //  [ 'posts', 'products' ]

  // 从外部数据源中获取数据
  let final = await getContents(types, apiURL)
  for(let [key, value] of Object.entries(final)) {
    // 1. 构建数据节点对象 allPostsContent allProductsContent
    console.log('key', key)
    const {createNodeFactory} = createNodeHelpers({
      typePrefix: key,
    })
    const createNodeObject = createNodeFactory('content')
    // 2. 根据数据节点对象对象创建节点
    value.forEach(item => {
      createNode(createNodeObject(item))
    })
  }
}

async function getContents(types, apiURL) {
  const size = types.length
  let index = 0
  // {posts: [], products: []}
  const final = {}

  await loadContents()

  async function loadContents () {
    if (index === size) return
    let {data} = await axios.get(`${apiURL}/${types[index]}`)
    final[types[index++]] = data
    await loadContents()
  }
  return final
}

module.exports = {
  sourceNodes,
}